package com.zwk.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zwk.base.handler.GuLiException;
import com.zwk.edu.entity.Chapter;
import com.zwk.edu.entity.Video;
import com.zwk.edu.entity.chapter.ChapterVo;
import com.zwk.edu.entity.chapter.VideoVo;
import com.zwk.edu.mapper.ChapterMapper;
import com.zwk.edu.mapper.VideoMapper;
import com.zwk.edu.service.ChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author zwk
 * @since 2022-08-22
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    @Autowired
    private ChapterMapper chapterMapper;

    @Autowired
    private VideoMapper videoMapper;

    // 查询课程大纲列表
    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {

        // 根据课程id查出所有章节
        QueryWrapper<Chapter> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("course_id", courseId);
        List<Chapter> chapterList = chapterMapper.selectList(wrapper1);

        // 根据课程id查出所有小节
        QueryWrapper<Video> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("course_id", courseId);
        List<Video> videoList = videoMapper.selectList(wrapper2);

        // 最终封装成的数据
        List<ChapterVo> chapterVoList = new ArrayList<>();

        // 封装章节数据
        for (Chapter chapter: chapterList
             ) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter, chapterVo);

            // 封装小节数据
            List<VideoVo> childrenList = new ArrayList<>();
            for (Video video: videoList
                 ) {
                if (video.getChapterId().equals(chapter.getId())){
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video, videoVo);
                    childrenList.add(videoVo);
                }
            }
            chapterVo.setChildren(childrenList);
            chapterVoList.add(chapterVo);
        }
        return chapterVoList;
    }

    // 删除章节内容
    @Override
    public void removeByCourseId(String courseId) {
        QueryWrapper<Chapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        chapterMapper.delete(wrapper);
    }
}
